package com.address.server;


import com.google.gson.Gson;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.address.AddressTool;
import org.address.DataTable;
import org.address.entity.StandardAddress;
import org.address.license.License;


import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class AddressServer {
    License ls =new License();
    static AddressTool ss = new AddressTool();
//    static AddressTool ss = new AddressTool("localhost",6379);
    static DataTable as = new DataTable();
    static Gson gson = new Gson();

    public static void main(String[] args) throws Exception {
        as.loadFromFile("D:\\","address.addr");
//        as.addressFix();

        System.out.println("用户地址 读取完毕！！！ ");
        as.initData(ss);

        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/standard", new MyHandler());
        server.createContext("/test", new MyHandler2());
        server.setExecutor(null);
        System.out.println("Starting server on port: 8000");
        server.start();
//        Thread.sleep(100000);
//        server.stop(1);
    }

    static class MyHandler implements HttpHandler {
        public void handle(HttpExchange t) throws IOException {
            String response = "{\"response\":\"地址解析错误\"}";

            String parmsStr = t.getRequestURI().getQuery();
            if(!parmsStr.isEmpty()){
                String[] parms = parmsStr.split("&");
                if(parms.length>0){
                    HashMap<String,String> keys = new HashMap<>();
                    for (String urlKey:parms){
                        if(urlKey.contains("=")){
                            String[] kv = urlKey.split("=");
                            keys.put(kv[0].toLowerCase(),kv[1]);
                        }
                    }
                    if(keys.containsKey("com/address")){
//                        System.out.println(keys);
                        StandardAddress resp = ss.getStdAddress(keys.get("com/address"));
//                        String json=JSON.toJSONString(resp);

                        if(resp.getAddress()!=null&& !resp.getAddress().isEmpty()){
                            String addressJson;
                            ArrayList<String> addrs = new ArrayList<>();
                            int i = 1;
                            for(Map.Entry<String,Map<String,String>> mp:resp.getAddress().entrySet()){
                                addressJson = gson.toJson(mp.getValue());
                                addrs.add(addressJson);
                            }
                            String mapJson =  gson.toJson(addrs);
//                            System.out.println(mapJson);
//                        response = "{\"testResponse\":\""+"江苏省南京市江宁区秣陵街道胜太社区双龙大道1539号51-1-1403"+"\"}";
//                            System.out.println(getEncoding(mapJson));
                            response = mapJson;
                        }

                    }
                }
            }

//            System.out.println(t.getRequestURI().getQuery());

            t.getResponseHeaders().set("Content-Type", "application/json");
//            t.getResponseHeaders().set("Content-Type", "text/html;charset=utf-8");
            t.sendResponseHeaders(200, 0);
            OutputStream os = t.getResponseBody();
            byte[] b = response.getBytes();
            for (int i = 0; i < b.length; i++) {
                os.write(b[i]);
            }
            os.close();
        }
    }

    static class MyHandler2 implements HttpHandler {
        public void handle(HttpExchange t) throws IOException {
            String response = "{\"testResponse\":\"Hello World2\"}";
            String parmsStr = t.getRequestURI().getQuery();
            if(!parmsStr.isEmpty()){
                String[] parms = parmsStr.split("&");
                if(parms.length>0){
                    HashMap<String,String> keys = new HashMap<>();
                    for (String urlKey:parms){
                        if(urlKey.contains("=")){
                            String[] kv = urlKey.split("=");
                            keys.put(kv[0].toLowerCase(),kv[1]);
                        }
                    }
                    if(keys.containsKey("com/address")){
                        System.out.println(keys);
                        StandardAddress resp = ss.getStdAddress("江苏省南京市江宁区秣陵街道胜太社区双龙大道1539号51-1-1403");
                        String mapJson =  gson.toJson(resp.getAddress());

                        response = "{\"testResponse\":"+gson.toJson(resp)+"}";
                        System.out.println(response);
//                        response = mapJson;
                    }
                }
            }
            t.getResponseHeaders().set("Content-Type", "application/json");
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

    public static String getEncoding(String str)
    {
        String encode;

        encode = "UTF-16";
        try
        {
            if(str.equals(new String(str.getBytes(), encode)))
            {
                return encode;
            }
        }
        catch(Exception ex) {}

        encode = "ASCII";
        try
        {
            if(str.equals(new String(str.getBytes(), encode)))
            {
                return "字符串<< " + str + " >>中仅由数字和英文字母组成，无法识别其编码格式";
            }
        }
        catch(Exception ex) {}

        encode = "ISO-8859-1";
        try
        {
            if(str.equals(new String(str.getBytes(), encode)))
            {
                return encode;
            }
        }
        catch(Exception ex) {}

        encode = "GB2312";
        try
        {
            if(str.equals(new String(str.getBytes(), encode)))
            {
                return encode;
            }
        }
        catch(Exception ex) {}

        encode = "UTF-8";
        try
        {
            if(str.equals(new String(str.getBytes(), encode)))
            {
                return encode;
            }
        }
        catch(Exception ex) {}

        /*
         *......待完善
         */

        return "未识别编码格式";
    }

}
